<template>
  <div class="contract-box">
    <div class="table">
      <div class="title">
        <div class="word">员工合同管理</div>
        <div class="add-btn">
          <el-button @click="addUser" type="warning" >添加新员工</el-button>
        </div>
      </div>
      <el-table
          :data="tableData"
          border style="width: 100%"
          stripe
          height="87vh"
          max-height="87vh"
      >
        <el-table-column
            type="index"
            width="50"
            align="center"
        />
        <el-table-column
            prop="name"
            label="员工姓名"
            align="center"
        />
        <el-table-column
            prop="started_at"
            label="合同起始日"
            align="center"
        />
        <el-table-column
            prop="deadline"
            label="合同中止日"
            align="center"
        />
        <el-table-column
            prop="status"
            label="合同状态"
            align="center"
        >
          <template #default="{ row }">
            <el-tag type="warning" v-if="compareDate(row.deadline)">合同已到期</el-tag>
            <el-tag type="success" v-else>合同期内</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="350"
            align="center"
        >
          <template #default="{ row }">
            <el-button
              @click="uploadContractFile(row)"
              type="primary"
              v-if="!row.status"
            >
              上传合同
            </el-button>
            <el-button
                @click="uploadContractFile(row)"
                type="success"
                v-if="compareDate(row.deadline) && row.status"
            >
              更新合同
            </el-button>
            <el-button
                @click="download(row)"
                v-if="row.status"
            >
              下载合同
            </el-button>
            <el-button
                @click="delCon(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!--添加新员工合同-->
  <el-dialog
      v-model="dialogVisible"
      width="500"
      class="dialog"
  >
    <div class="add-user-form">
      <div class="title">
        添加新的员工合同
      </div>
      <el-input v-model="newUser.userName" placeholder="员工姓名" />
      <div class="time-picker">
        <el-date-picker
            v-model="newUser.startTime"
            type="date"
            placeholder="合同起始日"
            size="default"
            value-format="YYYY-MM-DD"
        />
        <el-date-picker
            v-model="newUser.deadline"
            type="date"
            placeholder="合同终止日"
            size="default"
            value-format="YYYY-MM-DD"
        />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddUser">
          确认添加
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--上传员工合同-->
  <div class="upload-box">
    <el-dialog
      v-model="isUploadShow"
      width="500"
      :before-close="cancelUpload"
    >
      <el-form
          :model="uploadForm"
          ref="uploadFormRef"
      >
        <!--<el-form-item>-->
        <el-upload
            class="upload-demo"
            name="file"
            :action="uploadURL"
            v-model:file-list="uploadForm.file"
            :auto-upload="false"
            :on-change="onchange"
            style="margin-bottom: 2vw"
        >
          <el-button>点击选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              单次只可上传一个文件,仅支持pdf格式
            </div>
          </template>
        </el-upload>
        <!--</el-form-item>-->
        <el-form-item  v-if="uploadType">
          <div class="time-picker">
            <el-date-picker
                v-model="updateUser.startTime"
                type="date"
                placeholder="合同起始日"
                size="default"
                value-format="YYYY-MM-DD"
            />
            <el-date-picker
                v-model="updateUser.deadline"
                type="date"
                placeholder="合同终止日"
                size="default"
                value-format="YYYY-MM-DD"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCon(uploadFormRef)">
            上传
          </el-button>
          <el-button @click="cancelUpload">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {ElButton, ElMessage, ElTable, ElTableColumn, ElTag, ElDialog, ElFormItem, ElForm, ElUpload} from "element-plus"
import {onMounted, reactive, ref} from "vue"
import {create, uploadContract, getConList, downloadcon} from "@/api/index.js"
import axios from "axios"
import {baseurl} from "@/api/http"


let tableData = ref()
let dialogVisible = ref(false)
let newUser = reactive({
  userName:'',
  deadline:'',
  startTime:''
})

//上传合同表单
const uploadForm = reactive({
  file:[]
})
//合同文件数组
const arr = ref([])
// 上传dialog显隐
const isUploadShow = ref(false)
const uploadFormRef = ref()
//上传的目标员工id
const currentId = ref('')
//更新表单
const updateUser = reactive({
  deadline:'',
  startTime:''
})
const uploadType = ref()


const downloadURL = `${baseurl}/downloadcon`
// const downloadURL = 'http://192.168.10.100:8000/downloadcon'
const uploadURL = `${baseurl}/uploadContract`
// const uploadURL = 'http://192.168.10.100:8000/uploadContract'


onMounted(()=>{
  getContractList()
})

// 获取合同列表
const getContractList = async () => {
  try {
    const {data:res} = await getConList()
    if(res.code ===200) {
      tableData.value = res.data
    } else {
      ElMessage({
        message:'获取员工合同列表失败',
        type:'warning'
      })
    }
  } catch (e) {
    console.log(e)
  }
}
// 上传用户合同
const uploadContractFile = (row) => {
  if(compareDate(row.deadline) && row.status){
    uploadType.value = true
  } else {
    uploadType.value = false
  }
  currentId.value = row.id
  isUploadShow.value = true
}

// 显示dialog
const addUser = () => {
  dialogVisible.value = true
}

// 下载合同
const download = async (row) => {
  try {
    // console.log(row)
    const res = await downloadcon({contractId : 'v3coc'})
    const blob = new Blob([res.data],{ type:'application/x-rar-compressed,charset=utf-8' });
    const filename = row.name+'.pdf' // 获取文件名

    // // 创建一个临时链接元素来触发下载
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (e){
    ElMessage({
      message:'下载失败',
      type:'error'
    })
    console.log(e)
  }
}

const compareDate = (inputDate) => {
  // 获取当前日期
  var currentDate = new Date();

  // 将传入的日期字符串转换为 Date 对象
  var inputDateArray = inputDate.split("-");
  var year = parseInt(inputDateArray[0]);
  var month = parseInt(inputDateArray[1]) - 1; // 月份是从0开始计数的，需要减1
  var day = parseInt(inputDateArray[2]);
  var inputDateObj = new Date(year, month, day);

  // 比较日期
  if (inputDateObj > currentDate) {
    // 传入的日期大于当前日期-没过期
    return false;
  } else {
    // 传入的日期小于等于当前日期-合同已过期
    return true;
  }
}

// 提交新建用户
const submitAddUser = async () =>{
  try {
// const {data:res} = await create({
    const data = await create({
      userName:newUser.userName,
      startTime:newUser.startTime,
      deadline:newUser.deadline
    })
    // if(res.code === 200){
    //   ElMessage({
    //     message:'创建成功！',
    //     type:'success'
    //   })
    //   dialogVisible.value = false
    //   newUser = {
    //     userName:'',
    //     deadline:'',
    //     startTime:''
    //   }
    //   getConList()
    // } else {
    //   ElMessage({
    //     message:'创建失败！',
    //     type:'warning'
    //   })
    //   dialogVisible.value = false
    //   newUser = {
    //     userName:'',
    //     deadline:'',
    //     startTime:''
    //   }
    // }
  } catch (e) {
    console.log(e)
  }
}

//删除员工
const delCon = async (row) => {

}
/*合同上传*/
// 关闭前回调
const closeDialog = () => {
  newUser = {
    userName:'',
    deadline:'',
    startTime:''
  }
  dialogVisible.value = false
}

const onchange = (file)=>{
  arr.value.push(file.raw)
}

// 取消上传
const cancelUpload = () => {
  // window.source()
  isUploadShow.value = false
  uploadForm.file = []
}

//上传
const submitCon = () => {
  window.source = axios.CancelToken.source(); // 这里初始化source对象
  const name = arr.value[0].name
  if(name.substr(name.lastIndexOf(".")+1) !== 'pdf'){
    isUploadShow.value = false
    uploadForm.file = []
    arr.value = []
    getContractList()
    currentId.value = ''
    return ElMessage({
      type:'error',
      message:'不支持除pdf以外格式的文件'
    })
  } else {
    if(arr.value.length === 0){
      return ElMessage({
        type:'warning',
        message:'请选择文件'
      })
    } else {
      let fd = new FormData();
      fd.append('file', arr.value[0])
      fd.append('id', currentId.value)
      if(uploadType.value){
        fd.append('updateStart', updateUser.startTime)
        fd.append('updateDead', updateUser.deadline)
      }
      axios({
        url: uploadURL,       //上传服务器接口
        method: 'post',
        data: fd,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      },  {
        cancelToken: window.source.token
      }).then((res) => {
        if(res.data.code === 200){
          ElMessage({
            message: '上传成功!',
            type: 'success',
          })
          currentId.value = ''
          getContractList()
          isUploadShow.value = false
          uploadForm.file = []
          arr.value = []
        } else if (res.data.code === 402) {
          ElMessage({
            message: '不支持除docx以外格式的文件',
            type: 'warning',
          })
          getContractList()
          isUploadShow.value = false
          uploadForm.file = []
          arr.value = []
          currentId.value = ''
        } else {
          ElMessage({
            message: '上传失败!',
            type: 'warning',
          })
          getContractList()
          isUploadShow.value = false
          uploadForm.file = []
          arr.value = []
          currentId.value = ''
        }
      })
    }
  }

}
</script>

<style scoped lang="less">
.contract-box{
  height: 104vh;
  width: 101vw;
  box-sizing: border-box;
  //padding-top: 2vh;
  padding-left: 7%;
  margin-left: 2vw;
  .table{
    width: 95%;
    height: 90%;
    .title{
      display: flex;
      justify-content: space-between;
    }
    .el-table{
      border-radius: 15px !important;
      box-shadow: 0 0 5px 5px lightgray;
      padding: 10px;
      box-sizing: border-box;
      .el-table--border .el-table__inner-wrapper {
        margin-bottom: 10px;
      }
    }
    .title{
      height: 9vh;
      letter-spacing: 1px;
      text-align: left;
      padding-left: 1vw;
      font-size: 2.8vh;
      line-height: 9vh;
    }
  }
}

.dialog{
  .add-user-form{
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    align-items: center;
    .title{
      margin-bottom: 2vh;
      font-size: 1.7vh;
    }
    .el-input{
      width: 95%;
      margin-bottom: 2vh;
    }

  }
}

.time-picker{
  margin-bottom: 2vh;
  display: flex;
  //flex-direction: column;
  justify-content: space-between;
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper, .el-date-editor.el-input__wrapper) {
    width: 45% !important;
  }
  .el-date-picker{
    :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper ){
      width: 40% !important;
    }
  }
}

:deep(.el-form-item__content ){
  justify-content: center !important;
}
</style>
